<template>
  <div class="vi-wrap">
    <slot />
  </div>
</template>
<script>
export default {
  name: 'Visible',
  props: {
    anchors: {
      type: Array,
      default: () => []
    },
    headerId: {
      type: String,
      default: 'hidden'
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isListen: false
    }
  },
  created() {
    this.addEventListener()
  },
  beforeDestroy() {
    this.removeEventListener()
  },
  activated() {
    this.addEventListener()
  },
  deactivated() {
    this.removeEventListener()
  },
  methods: {
    switchAnchor(e) {
      if (sessionStorage.getItem('__scroll')) {
        sessionStorage.removeItem('__scroll')
        return
      }
      const innerHeight = window.innerHeight
      const headerEl = document.querySelector(`#${this.headerId}`)
      if (headerEl) {
        const top = headerEl.getBoundingClientRect().top
        if (top >= 0) {
          this.$emit('input', 'hidden')
          return
        }
      }
      for (const a of this.anchors) {
        const { value } = a
        const el = this.$el.querySelector(`#${value}`)
        if (el) {
          const { top, height } = el.getBoundingClientRect()
          if (top > 0 && top <= innerHeight - 10) {
            this.$emit('input', value)
          } else if (top < 0) {
            if (height + top > 0.6 * height) {
              this.$emit('input', value)
            }
          }
        }
      }
    },
    addEventListener() {
      if (this.isListen) {
        return
      }
      this.isListen = true
      window.addEventListener('scroll', this.switchAnchor, { passive: true })
    },
    removeEventListener() {
      if (!this.isListen) return
      this.isListen = false
      window.removeEventListener('scroll', this.switchAnchor, { passive: true })
    }
  }
}
</script>
<style lang="less" scoped>
.vi-wrap {
  // width: 100vw;
}
</style>
